<?php

namespace app\admin\controller\order;

use app\admin\logic\KuaiDi;
use app\admin\model\Admin;
use app\common\controller\Backend;
use app\common\model\order\OrderAction;
use app\common\model\order\OrderExpress;
use app\common\model\order\OrderStatementModel;
use app\common\model\order\OrderUniqueModel;
use app\common\model\User;
use Exception;
use PDOException;
use think\Db;
use think\exception\ValidateException;
use think\response\Json;

/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\order\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\order\Order;
        $this->view->assign("orderSettlementTypeList", $this->model->getOrderSettlementTypeList());
        $this->view->assign("isSettlementList", $this->model->getIsSettlementList());
        $this->view->assign("isPayList", $this->model->getIsPayList());
        $this->view->assign("payTypeList", $this->model->getPayTypeList());
//        $this->view->assign("settlementPayTypeList", $this->model->getSettlementPayTypeList());
        $this->view->assign("isCloseList", $this->model->getIsCloseList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("isSalesList", $this->model->getIsSalesList());
        $this->view->assign("platformList", $this->model->getPlatformList());
        $this->view->assign("isBurstOrderList", $this->model->getIsBurstOrderList());
//        $this->view->assign("getExpressList", $this->model->getExpressList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->with(['user','shop','claimshop'])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    /**
     * 编辑状态
     *
     * @return string
     * @throws \think\Exception
     */
    public function edit_status()
    {
        $row = $this->model->get($this->request->post('order_id'));
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            $params = $this->preExcludeFields($params);
//            $result = false;
            Db::startTrans();
            try {
                // 设为已支付
                if (isset($params['paystate'])) {
                    $this->model->setPay($row, $this->auth->id);
                }
                // 取消/设为已完成
                if (isset($params['orderstate'])) {
                    $this->model->setStatus($row, $this->auth->id, $params['orderstate']);
                }

//                $result = $row->allowField(true)->save($params);
                Db::commit();
            } catch (ValidateException | PDOException | Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success();
        }
    }


    /**
     * 详情
     */
    public function detail($ids = null)
    {
        $row = $this->model->get($ids,['item' => function($query){
            $query->with('spec');
        },'user','express','action','shop','claimshop']);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if($row->action){
            foreach ($row->action as $action){
                switch ($action->oper_type){
                    case 'user':
                        $user = User::get($action->oper_id);
                        $action->oper_type_text = !empty($user)?"用户($user->nickname)":'用户';
                        break;
                    case 'admin':
                        $admin = Admin::get($action->oper_id);
                        $action->oper_type_text = !empty($admin)?"管理员($admin->nickname)":'管理员';
                        break;
                    case 'system':
                        $action->oper_type_text = '系统';
                        break;
                }
            }
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 获取快递公司列表
     *
     * @return string|Json
     * @throws \think\Exception
     */
    public function getShipperList()
    {
        $list = $this->model->getExpressList();
        $total = count($list);
        return Json(['list' => $list,'total' => $total]);
    }

    /**
     * 发货
     */
    public function send()
    {
        $row = $this->model->get($this->request->post('order_id'));
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            $params = $this->preExcludeFields($params);
            $result = false;
            Db::startTrans();
            try {
                $Express = new \app\common\library\Express();

                $express_no = $params['express_no'];
                $express_name = $params['express_name'];
                $express_code = model('app\common\model\KuaidiModel')->where(['name' => $express_name])->value('code');

                // 查询是否存在,如果存在绕过快递100订阅
                $is_express_no = model('app\common\model\KuaidiSubModel')->where(['express_no' => $express_no])->count();

                // 订阅快递查询
                $express_params = [];
                if ($is_express_no == 0) {
                    $return_code = $Express->subScribe($express_name, $express_no, $row->mobile);
                    if ($return_code['returnCode'] != 200) {
                        throw new Exception('快递订阅接口异常-'.$return_code['message']);
                    }
                    $express_params[] = [
                        'sign' => $Express->sign($express_no),
                        'express_no' => $express_no,
                        'returncode' => $return_code['returnCode'],
                        'message' => $return_code['message']
                    ];
                }

                $order_express_params = [
                    'user_id' => $row->user_id,
                    'order_id' => $row->id,
                    'express_name' => $express_name,
                    'express_code' => $express_code,
                    'express_no' => $express_no,
                    'createtime' => time(),
                ];
                OrderExpress::create($order_express_params);

                // 更改订单状态
                $new_params['status'] = 2; // 订单状态:0=待支付,1=已支付/待发货,2=待收货,3=已收货,4=交易完成,5=已取消
                $new_params['is_delivery'] = 1; // 是否发货:0=未发货,1=已发货
                $new_params['delivery_time'] = time(); // 发货时间
                $row->dispatch_status = 1;
                $oper = [
                    'id' => $this->auth->id,
                ];
                OrderAction::operAdd($row, null, $oper, 'admin', '订单已发货');

                $result = $row->allowField(true)->save($new_params);

                // 写入快递订阅列表
                if ($express_params) model('app\common\model\KuaidiSubModel')->saveAll($express_params);

                Db::commit();
            } catch (ValidateException | PDOException | Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
    }

    /**
     * 修改信息
     */
    public function edit_info($id = null)
    {
        $row = $this->model->get($id);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            $params = $this->preExcludeFields($params);
            $result = false;
            Db::startTrans();
            try {
                $new_params = [];
                $oper = [
                    'id' => $this->auth->id,
                ];
                // 改价
                if($params['field'] == 'total_fee'){
                    if($row->last_total_fee == 0){
                        $new_params['last_total_fee'] = $row->total_fee;
                    }
                    $new_params['total_fee'] = $params['value'];
                    OrderAction::operAdd($row, null, $oper, 'admin', "订单价格已更改:".$params['value']);

                    // 同步修改主订单价格 2022-11-30 14:17:45
                    $new_total_fee = $row->total_fee - $new_params['total_fee'];
                    OrderUniqueModel::where(['order_unique_no' => $row->order_unique_no])->setInc('need_price',$new_total_fee);
                }
                if($params['field'] == 'remark'){
                    $new_params['remark'] = $params['value'];
                    OrderAction::operAdd($row, null, $oper, 'admin', "订单备注已修改:".$params['value']);
                }
                $result = $row->allowField(true)->save($new_params);

                Db::commit();
            } catch (ValidateException | PDOException | Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
    }


    /**
     * 收款完成
     */
    public function settlement($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
//        if($row->order_settlement_type != 'credit' || $row->is_settlement != 0 || $row->is_sales != 0 || $row->is_pay != 0 || $row->is_close != 0){
        if($row->order_settlement_type != 'credit' || $row->is_settlement != 0 || $row->is_sales != 0 || $row->is_close != 0){
            $this->error(__('状态错误'),'order/order/index');
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');
            if (empty($params)) {
                $this->error(__('Parameter %s can not be empty', ''));
            }
            $params['is_settlement'] = 1; // 账期结算:0=未结算,1=已结算
            $params['pay_time'] = time();
            $result = false;
            Db::startTrans();
            try {
                $oper = [
                    'id' => $this->auth->id,
                ];
                OrderAction::operAdd($row, null, $oper, 'admin', '账期订单收款完成:'.$params['pay_price']);

                // 生成账单
                OrderStatementModel::operAdd('order', $row);

                $result = $row->allowField(true)->save($params);

                Db::commit();
            } catch (ValidateException | PDOException | Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success();
            } else {
                $this->error(__('No rows were updated'));
            }
        }
        return $this->view->fetch();
    }

}
